package com.space.rabbitmq.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 消息消费者2
 *
 * @author zhanglei
 */
@Component
public class SecondConsumer {

    /**
     * "first-queue","second-queue"
     *
     * @param message
     * @throws Exception
     */
    @RabbitListener(queues = {"second-queue"})
    public void handleMessage(String msg, Channel channel, Message message) throws Exception {
        // 处理消息
        System.out.println("SecondConsumer --- handleMessage：" + message);
        try {
//            System.out.println("【SecondConsumer成功接收到消息】>>>：" + msg);
            // 确认收到消息，只确认当前消费者的一个消息收到
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                System.out.println("【SecondConsumer】消息已经回滚过，拒绝接收消息：" + msg);
                // 拒绝消息，并且不再重新进入队列
                //public void basicReject(long deliveryTag, boolean requeue)
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                System.out.println("【SecondConsumer】消息即将返回队列重新处理：" + msg);
                //设置消息重新回到队列处理
                // requeue表示是否重新回到队列，true重新入队
                //public void basicNack(long deliveryTag, boolean multiple, boolean requeue)
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
            e.printStackTrace();
        }
    }
}
